<?php
namespace Admin\Controller;

use Think\Controller;

/**
 * 公用类
 * @author Administrator
 *
 */
class CommController extends Controller {

	/**
	 * 单条信息
	 *
	 * @var array
	 */
	protected $dataInfo;

	/**
	 * 数据列表
	 *
	 * @var array
	 */
	protected $dataList;

	/**
	 * 模型
	 *
	 * @var array
	 */
	protected $model;
	
	/**
	 * 参数数组
	 * 
	 * @var array
	 */
	protected $paramter;
	
	/**
	 * 会员信息
	 * 
	 * @var array
	 */
	protected $user;


	/**
	 * 构造方法
	 */
	public function _initialize() {
		//判断是否为Ajax访问
		if (! IS_AJAX && strpos ( "|Index|File|", "|" . CONTROLLER_NAME . "|" ) === false) {
			$this->error ( '非法访问!' );
		}
		// 如果是uploadify上传文件，则不检测是否登录（此地方为一个暂未解决的bug，uploadify上传session的问题）
		if (CONTROLLER_NAME != "File") {
			$this->checkLogin ();
		}
	}

	/**
	 * 检测用户是否登录
	 */
	private function checkLogin() {
		$userAuth = session ( 'userAuth' );
		if ( empty( $userAuth ) ) {
			if ( CONTROLLER_NAME == 'Index' ) {
				$this->redirect( 'Login/index' );
			} else {
				echo "<script> window.top.location.href='/Admin/Login/index';</script>";
			}
			die();
		} else {
			$map ['username'] = array ( 'eq', $userAuth ['username'] );
			$map ['is_delete'] = 0;
			$map ['status'] = 0;
			$this->user = D ( 'User' )->where ( $map )->find ();
			if (empty ( $this->user )) {
				session ( 'userAuth', null );
				if ( CONTROLLER_NAME == 'Index' ) {
					$this->redirect( 'Login/index' );
				} else {
					$this->display( 'Login/login1' );
				}
				die();
			} else {
				// 获取当前管理员的权限
				$this->user['authString'] = $this->formatAuth();
				// 判断是否有权限
				$action = ',' . CONTROLLER_NAME . '/' . ACTION_NAME . ',';
				/*if ( strpos( $this->user['authString'], $action ) === false && $this->user['id'] != 1 ) {
					if ( IS_AJAX ) {
						$this->dwzSuccess( '很抱歉，您还没拥有此权限!', 0, strtolower( CONTROLLER_NAME ), 'refreshClose' );
					} else {
						session ( 'userAuth', null );
						$this->error( '很抱歉，您没有权限!', U( 'Login/index' ) );exit;
					}
				}*/
				$this->assign ( 'userAuth', $this->user );
			}
		}
	}

	/**
	 * 获取数据列表[分页-数组条件array]
	 *
	 * @param $model Model
	 * @param $condition 查询条件
	 * @param int $pageSize 每页显示条数
	 * @param string $order 排序
	 * @return array
	 */
	public function getPageList($model, $condition, $pageSize = 20, $order = "sort desc") {
		if (is_array ( $condition )) {
			$condition ['is_delete'] = 0;
		}
		$page ['all'] = $model->where ( $condition )->count ( 'id' );
		$page ['numPerPage'] = I ( 'post.numPerPage', $pageSize );
		$page ['totalPage'] = intval ( $page ['all'] ) / intval ( $page ['pageSize'] );
		$page ['totalPage'] = is_float ( $page ['totalPage'] ) ? intval ( $page ['totalPage'] ) + 1 : $page ['totalPage'];
		$page ['pageNum'] = I ( 'post.pageNum', 1 );
		$page ['numPerPageArray'] = array ( 5, 10, 20, 30, 40, 50 );
		$limitStart = ($page ['pageNum'] - 1) * $page ['numPerPage'];
		$limit = array( 'begin' => $limitStart, 'num' => $page ['numPerPage'] );
		// 注入分页数据
		$this->assign ( "page", $page );

		// 返回数据
		return $model->getList($condition, "*", $limit, $order);
	}
	
	/**
	 * 获取数据列表[分页-sql条件]
	 *
	 * @param $model Model
	 * @param $sql 查询语句
	 * @param int $pageSize 每页显示条数
	 * @param string $order 排序
	 * @return array
	 */
	public function getPageSQLList($model, $sql, $pageSize = 20, $order = "a.sort desc") {
		$page ['all'] = count ( $model->query( $sql ) );
		$page ['numPerPage'] = I ( 'post.numPerPage', $pageSize );
		$page ['totalPage'] = intval ( $page ['all'] ) / intval ( $page ['pageSize'] );
		$page ['totalPage'] = is_float ( $page ['totalPage'] ) ? intval ( $page ['totalPage'] ) + 1 : $page ['totalPage'];
		$page ['pageNum'] = I ( 'post.pageNum', 1 );
		$page ['numPerPageArray'] = array ( 5, 10, 20, 30, 40, 50 );
		
		$limitStart = ($page ['pageNum'] - 1) * $page ['numPerPage'];
		$limit = array( 'begin' => $limitStart, 'num' => $page ['numPerPage'] );

		// 注入分页数据
		$this->assign ( "page", $page );

		// 返回数据
		return $model->getSQLList( $sql, "*", $limit, $order);
	}

	/**
	 * 获取数据列表
	 * @param object $model 模型名
	 * @param array $condition 查询条件
	 * @param string $field 查询字段
	 * @param string $order 排序条件
	 */
	public function getList( $model, $condition, $field = "*", $order = "sort desc" ) {
		return $model->where( $condition )->field( $field )->order( $order )->select();
	}
	
	/**
	 * 格式化权限
	 * 
	 * @return string
	 */
	private function formatAuth() {
		$auth = $this->getAllAuth( $this->user['auth'] );
		//return implode( ",", array_unique( array_filter( explode( ",", $auth ) ) ) );
                return $auth;
	}
	
	/**
	 * 递归取得当前管理员的所有权限
	 */
	private function getAllAuth( $authId, $authString = "" ) {
		$parent = D( 'UserRole' )->getOne( $authId, 'id' );
		$authString .= $parent['auth'];
		// 判断是否继承上级权限
		if ( empty( $parent['inherit'] ) ) {
			return $authString;
		} else {
			return $this->getAllAuth( $parent['pid'], $authString );
		}
	}

	/**
	 * 显示添加页面
	 */
	public function add() {
		$activename = CONTROLLER_NAME;
		$type 	= I ( 'get.type', 0);
		if($type)
			$this->assign ( 'type', $type );

		// 渲染视图
		$this->display ();
	}

	/**
	 * 插件一条数据
	 */
	public function create() {
		$modelName = CONTROLLER_NAME;
		if($modelName == 'Welfare'){
			$_POST['uid'] = $this->user['id'];
		}
		if($_POST['discount_start']){
			$_POST['discount_start'] = strtotime($_POST['discount_start']);
		}
		if($_POST['discount_end']){
			$_POST['discount_end'] = strtotime($_POST['discount_end']);
		}
		//判断  当时商铺管理员修改商品的时候   存入商铺下品牌id、
		if($modelName == 'Product'){
			$auth = $this->user['auth'];
			if($auth == '2'){
				$uid = $this->user['id'];
				$ids =  D('Welfare')->field('id')->where("title='".$_POST['brand']."' and uid=".$uid)->find();
				$_POST['brandid'] = $ids['id'];
			}
		}
		$model = D ( $modelName );
		$refresh = $_POST ['refresh'] ? $_POST ['refresh'] : 'refreshClose';
		$return = $model->commInsert ( $_POST );
		$this->dwzSuccess ( $return ['info'], $return ['status'], $modelName, $refresh );
	}

	/**
	 * 显示编辑页面
	 */
	public function edit() {

		$activename = CONTROLLER_NAME;
		$id 	= I ( 'get.id' );
		$modelName = CONTROLLER_NAME;
		$model = D ( $modelName );
		$return = $model->getCommOne ( $id );
		if ($return ['status']) {
			$this->assign ( 'dataInfo', $return ['info'] );
		} else {
			die ( $return ['info'] );
		}
		
		
		
		$this->display ();
	}

	/**
	 * 修改一条数据
	 */
	public function update() {
		$modelName = CONTROLLER_NAME;
		$model = D ( $modelName );
		if($_POST['discount_start']){
			$_POST['discount_start'] = strtotime($_POST['discount_start']);
		}
		if($_POST['discount_end']){
			$_POST['discount_end'] = strtotime($_POST['discount_end']);
		}
		//判断  当时商铺管理员修改商品的时候   存入商铺下品牌id、
		if($modelName == 'Product'){
			$auth = $this->user['auth'];
			if($auth == '2'){
				$uid = $this->user['id'];
				$ids =  D('Welfare')->field('id')->where("title='".$_POST['brand']."' and uid=".$uid)->find();
				$_POST['brandid'] = $ids['id'];
			}
		}
		

		$refresh = $_POST ['refresh'] ? $_POST ['refresh'] : 'refreshClose';
		$return = $model->commUpdate ( $_POST );
		$this->dwzSuccess ( $return ['info'], $return ['status'], $modelName, $refresh );
	}

	/**
	 * 删除一条或一组数据(伪删除)
	 */
	public function remove() {
	 $idList = I ( 'post.id' );
	 $modelName = CONTROLLER_NAME;
	 if($modelName=='Panicbuy' or $modelName=='Product' or $modelName=='Welfare' or $modelName=='Taskclass' or $modelName=='Groupbuy')
		{
			$model=D('AllOrderlist');
		}
	 else
	    {
			$model = D ( $modelName );
		}
		
		$return = $model->commRemove ( $idList );
		$this->dwzSuccess ( $return ['info'], $return ['status'], $modelName, "refreshThis" );
	}

	/**
	 * 获取数据id字符串
	 * @param array $data 数据数组
	 * @return string
	 */
	public function getIdList($data) {
		$idList = "";
		for($i = 0, $size = count ( $data ); $i < $size; $i ++) {
			$idList .= empty ( $idList ) ? $data [$i] ['id'] : "," . $data [$i] ['id'];
		}
		return $idList;
	}

	/**
	 * 设置一条或一组数据的状态
	 */
	public function commSetStatus() {
		$idList = $_REQUEST ['id'];
		$param = I ( 'get.param' );
		$modelName = CONTROLLER_NAME;
		$model = D ( $modelName );
		$return = $model->commSetStatus ( $idList, explode ( "-", $param ) );
		$this->dwzSuccess ( $return ['info'], $return ['status'], $modelName, "refreshThis" );
	}


	public function getCity(){
		$return = returnArray( array( 'status' => 0, 'info' => '' ) );
		$id = I( 'post.id', '' );
		if ( is_number( $id ) ) {
			$return['info'] = '获取错误!';
		} else {
			$tempArray = D('HatCity')->where(array('father'=>$id))->select();
			foreach ($tempArray as $key=>$val){
			    $tempArray[$key]['id'] = $val['city_id'];
			    $tempArray[$key]['title'] = $val['city'];
			}
			if ( empty( $tempArray ) ) {
				$return['info'] = '没有数据';
			} else {
				$return['status'] = 1;
				$return['info'] =$tempArray;
			}
		}
		if ( empty( $return['status'] ) ) {
			$this->dwzSuccess( $return['info'], 0, '', 'refreshThis' );
		} else {
			$this->ajaxReturn( $return );
		}
    }


    public function getArea(){
        $return = returnArray( array( 'status' => 0, 'info' => '' ) );
        $id = I( 'post.id', '' );
        if ( is_number( $id ) ) {
            $return['info'] = '获取错误!';
        } else {
            $tempArray = D('HatArea')->where(array('father'=>$id))->select();
            foreach ($tempArray as $key=>$val){
                $tempArray[$key]['id'] = $val['area_id'];
                $tempArray[$key]['title'] = $val['area'];
            }
            if ( empty( $tempArray ) ) {
                $return['info'] = '没有数据';
            } else {
                $return['status'] = 1;
                $return['info'] =$tempArray;
            }
        }
        if ( empty( $return['status'] ) ) {
            $this->dwzSuccess( $return['info'], 0, '', 'refreshThis' );
        } else {
            $this->ajaxReturn( $return );
        }
    }
}